<?php

namespace App\Service;

use App\Exceptions\AuthException;
use App\Models\User;
use Illuminate\Http\Request;

class AuthService
{
    protected TokenService $tokenService;

    public function __construct(TokenService $tokenService)
    {
        $this->tokenService = $tokenService;
    }

    /**
     * 检查是否登录和是否有当前访问节点的权限
     * @throws AuthException
     */
    public function checkAuth(Request $request): array|\Illuminate\Http\JsonResponse
    {
        $token = $request->header('Authorization');
        $user = $this->tokenService->getUserByToken($token);
        if (!$user) {
            // token无效
            throw new AuthException('token失效，请重新登录');
        } else {
            if ($user['name'] === 'admin') {
                return $user;
            } else {
                // 检查权限
                $action = $this->getActionByController($request->route()->action['controller']);
                $auths = $this->getActions($user);
                if (in_array($action, $auths)) {
                    return $user;
                } else {
                    throw new AuthException('没有权限，请联系管理员授权');
                }
            }
        }
    }

    /**
     * 获取控制器和方法
     * @param string $controller
     * @return string
     */
    private function getActionByController(string $controller): string
    {
        // 获取控制器和方法，如App\Http\Controllers\IndexController@index 则返回IndexController@index
        // 获取最后一个\后的内容
        $controller = explode('\\', $controller);
        return end($controller);
    }

    /**
     * 获取用户权限
     * @param array $user
     * @return array
     */
    private function getActions(array $user): array
    {
        $user = User::find($user['id']);
        // 根据用户id获取用户权限
        $roles = $user->roles()->with('nodes')->get()->toArray();
        $auths = [];
        foreach ($roles as $role) {
            foreach ($role['nodes'] as $node) {
                $auths[] = $node['path'];
            }
        }
        return $auths;
    }
}
